//
// Created by 215609 on 2024/8/7.
//

#include "AVPlayer.h"

void AVPlayer::init(JNIEnv *jniEnv, jobject obj, char *url, int renderType, jobject surface) {

    jniEnv->GetJavaVM(&m_JavaVM);
    m_JavaObj = jniEnv->NewGlobalRef(obj);


    videoDecoder=new VideoDecoder(url);

    audioDecoder=new AudioDecoder(url);
    //设置渲染模式
    if (renderType==VIDEO_RENDER_ANWINDOW){
    m_VideoRender= new NativeWindowRender(jniEnv, surface);
    videoDecoder->SetVideoRender(m_VideoRender);
    }

    m_OpenSLRender=new OpenSLRender();
//    m_AAudioRender=new AAudioRender();
//            m_AudioRender = new OpenSLRender();
    audioDecoder->setAudioRender(m_OpenSLRender);

//    audioDecoder->

//    audioDecoder->
    //设置java回调
    audioDecoder->SetMessageCallback(this,PostMessage);
    videoDecoder->SetMessageCallback(this,PostMessage);

}

void AVPlayer::Stop(){
    videoDecoder->Stop();
}

void AVPlayer::PostMessage(void *context, int msgType, float msgCode) {
    if (context!= nullptr){
        BasePlayer *player=static_cast<BasePlayer *>(context);
        bool isAttach = false;
        //通过JVM虚拟机获取JNIEnv
        JNIEnv *env = player->GetJNIEnv(&isAttach);

        if (env== nullptr){
            return;
        }

        jobject javaObj=player->GetJavaObj();

        jmethodID  mid=env->GetMethodID(env->GetObjectClass(javaObj),JAVA_PLAYER_EVENT_CALLBACK_API_NAME, "(IF)V");

        env->CallVoidMethod(javaObj,mid,msgType,msgCode);
//        jobject javaObj=player->Get
        if(isAttach)
            player->GetJavaVM()->DetachCurrentThread();

    }



}

jobject AVPlayer::GetJavaObj() {
    return m_JavaObj;
}
void AVPlayer::UnInit() {
    if (m_VideoRender){
        delete m_VideoRender;
        m_VideoRender= nullptr;
    }

    if (m_VideoRender){
        delete m_VideoRender;
        m_VideoRender = nullptr;
    }

    bool isAttach = false;
    GetJNIEnv(&isAttach)->DeleteGlobalRef(m_JavaObj);
    if(isAttach)
        GetJavaVM()->DetachCurrentThread();

}

void AVPlayer::Play() {
    if (videoDecoder!=nullptr){
        LOGCATE("AVPlayer_play11");
        videoDecoder->Start();
    }


    if (audioDecoder!=nullptr){
        LOGCATE(" audio AVPlayer_play11");
        audioDecoder->Start();
    }

}
JavaVM *AVPlayer::GetJavaVM() {
    return m_JavaVM;
}

JNIEnv *AVPlayer::GetJNIEnv(bool *isAttach) {
    JNIEnv *env;

    int status;

    if (nullptr==m_JavaVM){
        return nullptr;
    }
    *isAttach = false;

    status = m_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_4);
    if (status != JNI_OK) {
        status = m_JavaVM->AttachCurrentThread(&env, nullptr);
        if (status != JNI_OK) {
            LOGCATE("FFMediaPlayer::GetJNIEnv failed to attach current thread");
            return nullptr;
        }
        *isAttach = true;
    }
    return env;
}
AVPlayer::AVPlayer() {


}
 AVPlayer:: ~AVPlayer() {
     if (videoDecoder!=nullptr){
         delete videoDecoder;
     }


}
